/**
 *
 * 入职登记，员工信息维护，员工信息查询的排序弹窗组件
 *
 * props: {
 *      visible: true|false  显示|隐藏,
 *      onClose: function() {}  关闭弹窗钩子,
 *      table: 平台的table对象,
 *      onSure: 点击确定按钮的回调,
 *      meta: 平台的meta对象,
 *      templateId: 排序模版对应的模版名称
 * }
 *
 */

import React, { Component } from 'react';
import './index.less';
import { base, toast } from 'nc-lightapp-front';
import initSortData from './functions/getInitSortData';
import saveSort from './functions/saveSort';
import cleanSortTable from './functions/cleanSortTable';

const { NCModal, NCSelect, NCButton, NCPopconfirm } = base;
const { Header: NCModalHeader, Body: NCModalBody, Footer: NCModalFooter } = NCModal;
const NCOption = NCSelect.NCOption;

class SortModal extends Component {
	constructor(props) {
		super(props);

		this.state = {
			allFields: [],
			selectedField: '',
			selectedAscendFlag: true,
			pkHrSort: ''
		};

		this.tableData = {};

		this.closeModal = this.closeModal.bind(this);
		this.showModalHandle = this.showModalHandle.bind(this);
		this.selectChangeHandle = this.selectChangeHandle.bind(this);
		this.addOneRow = this.addOneRow.bind(this);
		this.saveSort = this.saveSort.bind(this);
		this.operateTable = this.operateTable.bind(this);
		this.exchangeTable = this.exchangeTable.bind(this);
		this.moveTableRow = this.moveTableRow.bind(this);
		this.removeTableRow = this.removeTableRow.bind(this);
		this.cleanTable = this.cleanTable.bind(this);
		this.getTableData = this.getTableData.bind(this);
		this.beSure = this.beSure.bind(this);
		this.processTemplate = this.processTemplate.bind(this);
	}

	processTemplate() {
		const { meta, templateId } = this.props;
		let template = meta.getMeta();
		if (template[templateId].items.length < 3) {
			template[templateId].items.forEach((item) => {
				item.width = '135px'; 
				item.itemtype = 'label';
			});
			template[templateId].items.push({
				itemtype: 'customer',
				width: '140px',
				label: this.props.json['hi6007-000029'] /* 国际化处理： 操作*/,
				visible: true,
				render: (text, record, index) => {
					return (
						<div className="sort-operate-box">
							<a href="javascript:void(0)" onClick={this.operateTable('exchange')(text, record, index)}>
								{this.props.json['hi6007-000079']}
								{/* 国际化处理： 切换*/}
							</a>
							<a href="javascript:void(0)" onClick={this.operateTable('delete')(text, record, index)}>
								{this.props.json['hi6007-000031']}
								{/* 国际化处理： 删除*/}
							</a>
							<a href="javascript:void(0)" onClick={this.operateTable('up')(text, record, index)}>
								{this.props.json['hi6007-000080']}
								{/* 国际化处理： 上移*/}
							</a>
							<a href="javascript:void(0)" onClick={this.operateTable('down')(text, record, index)}>
								{this.props.json['hi6007-000081']}
								{/* 国际化处理： 下移*/}
							</a>
						</div>
					);
				}
			});
			meta.setMeta(template);
		}
	}

	beSure() {
		this.saveSort().then((res) => {
			if (res.success) {
				this.closeModal();
				if (this.tableData.rows.length === 0) {
					toast({ color: 'danger', content: this.props.json['hi6007-000182'] });
					/* 国际化处理： 没有设置排序字段！*/
					return;
				}
				this.props.onSure && this.props.onSure();
			}
		});
	}

	cleanTable() {
		const { templateId, editTable } = this.props;

		this.tableData = {
			areacode: templateId,
			rows: []
		};
		this.saveSort().then((res) => {
			if (res.success) {
				cleanSortTable({
					pk_hr_sort: this.state.pkHrSort
				}).then((res) => {
					if (res.success) {
						editTable.setTableData(templateId, this.tableData);
					}
				});
			}
		});
	}

	operateTable(type) {
		return (text, record, index) => {
			return () => {
				if (type === 'exchange') {
					this.exchangeTable(text, record, index);
				} else if (type === 'delete') {
					this.removeTableRow(index);
				} else if (type === 'up' || type === 'down') {
					this.moveTableRow(text, record, index, type);
				}
			};
		};
	}

	exchangeTable(text, record, index) {
		let ascendFlag = this.tableData.rows[index].values['ascend_flag'];

		ascendFlag.value = !ascendFlag.value;
		ascendFlag.display = ascendFlag.value ? this.props.json['hi6007-000077'] : this.props.json['hi6007-000178'];
		/* 国际化处理： 升序,降序,降序*/

		this.props.editTable.setTableData('sort', this.tableData);
	}

	removeTableRow(index) {
		const { templateId, editTable } = this.props;
		this.tableData.rows.splice(index, 1);
		editTable.setTableData(templateId, this.tableData);
	}

	moveTableRow(text, record, index, type) {
		const { templateId, table } = this.props;

		if ((type === 'up' && index === 0) || (type === 'down' && index === this.tableData.rows.length - 1)) {
			return;
		}
		let row = this.tableData.rows;

		if (type === 'up') {
			row.splice(index - 1, 0, row.splice(index, 1)[0]);
		} else if (type === 'down') {
			row.splice(index + 1, 0, row.splice(index, 1)[0]);
		}

		table.setAllTableData(templateId, this.tableData);
	}

	saveSort() {
		let postData = {
			func_type: 3,
			pk_hr_sort: this.state.pkHrSort,
			sort_con_str: []
		};

		this.tableData.rows.map((item, index) => {
			postData.sort_con_str.push({
				field_seq: index,
				ascend_flag: item.values['ascend_flag'].value,
				field_code: item.values['field_code'].value,
				field_name: item.values['field_code'].display
			});
		});

		return saveSort(postData);
	}

	addOneRow() {
		const { editTable, templateId } = this.props;
		let { selectedField, allFields, selectedAscendFlag } = this.state;

		let selectedFieldObject = allFields.filter((item) => item.value === selectedField);

		let rowData = {
			field_code: {
				display: selectedFieldObject[0].title,
				value: selectedFieldObject[0].value,
				scale: -1
			},
			ascend_flag: {
				display: selectedAscendFlag
					? this.props.json['hi6007-000077']
					: this.props.json['hi6007-000178'] /* 国际化处理： 升序,降序,降序*/,
				value: selectedAscendFlag,
				scale: -1
			}
		};
		let isExist = false;

		this.tableData.rows.map((item) => {
			if (item.values.field_code.value === selectedField) {
				isExist = true;
			}
		});

		if (isExist === false) {
			this.tableData.rows.push({
				values: rowData
			});
		}

		editTable.setTableData(templateId, this.tableData);
	}

	selectChangeHandle(type) {
		return (value) => {
			let field = type === 'field' ? 'selectedField' : 'selectedAscendFlag';

			this.setState({
				[field]: value
			});
		};
	}

	showModalHandle() {
		this.processTemplate();
		this.getTableData();
	}

	getTableData() {
		const { editTable, templateId } = this.props;
		initSortData({
			func_type: 3
		}).then((res) => {
			if (res.success) {
				let tableData = this.processTableData(res.data.defaultFields);
				let allFields = this.processAllFields(res.data.allFields);

				this.tableData = tableData;
				editTable.setTableData(templateId, tableData);
				this.setState({
					allFields: allFields,
					selectedField: allFields[0].value,
					pkHrSort: res.data.pkHrSort
				});
			}
		});
	}

	processAllFields(data) {
		let result = [];

		data.map((item) => {
			result.push({
				value: item.code,
				title: item.name
			});
		});

		return result;
	}

	processTableData(data) {
		let result = {
			areacode: this.props.templateId,
			rows: []
		};

		data.map((item) => {
			result.rows.push({
				values: {
					field_code: {
						display: item.field_name,
						value: item.field_code,
						scale: -1
					},
					ascend_flag: {
						value: item.ascend_flag,
						display: item.ascend_flag
							? this.props.json['hi6007-000077']
							: this.props.json['hi6007-000178'] /* 国际化处理： 升序,降序,降序*/,
						scale: -1
					}
				}
			});
		});
		return result;
	}

	closeModal() {
		this.props.onClose && this.props.onClose();
	}

	render() {
		const { visible, editTable, templateId } = this.props;
		const { allFields, selectedAscendFlag, selectedField } = this.state;

		return (
			<NCModal
				show={visible}
				className="sort-modal-wrapper"
				size="sm"
				onHide={this.closeModal}
				onEntered={this.showModalHandle}
				backdrop={'static'}
			>
				<NCModalHeader closeButton={true}>
					{this.props.json['hi6007-000068']}
					{/* 国际化处理： 排序*/}
				</NCModalHeader>
				<NCModalBody>
					<div className="sort-modal-content">
						<label className="sort-modal-label">{this.props.json['hi6007-000082']}</label>
						{/* 国际化处理： 排序方式*/}
						<NCSelect
							className="sort-modal-select"
							value={selectedField}
							onChange={this.selectChangeHandle('field')}
						>
							{allFields.map((item) => {
								return <NCOption value={item.value}>{item.title}</NCOption>;
							})}
						</NCSelect>
						<NCSelect
							className="sort-type-select"
							value={selectedAscendFlag}
							onChange={this.selectChangeHandle('type')}
						>
							<NCOption value={true}>
								{this.props.json['hi6007-000077']}
								{/* 国际化处理： 升序*/}
							</NCOption>
							<NCOption value={false}>
								{this.props.json['hi6007-000178']}
								{/* 国际化处理： 降序*/}
							</NCOption>
						</NCSelect>
						<div className="sort-modal-button-wrapper">
							<NCButton colors="border" onClick={this.addOneRow}>
								{this.props.json['hi6007-000083']}
								{/* 国际化处理： 增加*/}
							</NCButton>
						</div>
						<div className="sort-modal-table">{editTable.createEditTable(templateId)}</div>
					</div>
				</NCModalBody>

				<NCModalFooter>
					<NCPopconfirm
						trigger="click"
						placement="top"
						content={this.props.json['hi6007-000078']} /* 国际化处理： 是否清空数据库中保存的排序条件？*/
						onClose={this.cleanTable}
						className="sort-modal-confirm-pop"
					>
						<NCButton shape="border" className="sort-clean-btn">
							{this.props.json['hi6007-000084']}
							{/* 国际化处理： 清空*/}
						</NCButton>
					</NCPopconfirm>
					<NCButton colors="primary" onClick={this.beSure}>
						{this.props.json['hi6007-000174']}
						{/* 国际化处理： 确认*/}
					</NCButton>
					<NCButton shape="border" onClick={this.saveSort}>
						{this.props.json['hi6007-000179']}
						{/* 国际化处理： 保存*/}
					</NCButton>
					<NCButton shape="border" onClick={this.closeModal}>
						{this.props.json['hi6007-000005']}
						{/* 国际化处理： 取消*/}
					</NCButton>
				</NCModalFooter>
			</NCModal>
		);
	}
}

export default SortModal;
